package com.huluobo.lc.kotlinim1812a

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.SoundPool
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.multidex.MultiDex
import cn.bmob.v3.Bmob
import cn.bmob.v3.util.BmobNotificationManager.showNotification
import com.huluobo.lc.kotlinim1812a.adapter.EMMessageListenerAdapter
import com.huluobo.lc.kotlinim1812a.ui.activity.ChatActivity
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMOptions
import com.hyphenate.chat.EMTextMessageBody

/**
 * @author Lc
 * @description: app入口,进行初始化
 * @date :2021/6/18 15:48
 */
class IMApplication : Application() {
    companion object {
        lateinit var instance: IMApplication
        //因为伴生函数类似静态代码块,在类的初始化时调用
        //也就是说会在onCreate之前调用,这样会产生空指针
        //使用lateinit,则在onCreate之后创建实例
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    val soundPool: SoundPool = SoundPool.Builder().setMaxStreams(10).build()

    val duan by lazy {
        soundPool.load(instance, R.raw.duan, 0)
    }

    val yulu by lazy {
        soundPool.load(instance, R.raw.yulu, 0)
    }

    private val messageListener = object : EMMessageListenerAdapter() {
        override fun onMessageReceived(messages: MutableList<EMMessage>?) {
            //判断,当前应用在前台或者后台
            if (isForeground()) {
                soundPool.play(duan, 1f, 1f, 0, 0, 1f)
            } else {
                soundPool.play(yulu, 1f, 1f, 0, 0, 1f)
                showNotification(messages)
            }
        }
    }

    private fun showNotification(messages: MutableList<EMMessage>?) {
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        messages?.forEach {
            var contentText = "非文本消息"
            if (it.type == EMMessage.Type.TXT) {
                contentText = (it.body as EMTextMessageBody).message
            }//[图片][视频][表情]

            val intent = Intent(this, ChatActivity::class.java)
            intent.putExtra("username", it.conversationId())

            val taskStackBuilder =
                TaskStackBuilder.create(this).addParentStack(ChatActivity::class.java)
                    .addNextIntent(intent)

            val pendingIntent =
                taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)

            val notification = Notification.Builder(this)
                .setContentTitle(getString(R.string.receive_new_message))
                .setContentText(contentText)
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.avatar1))
                .setSmallIcon(R.mipmap.ic_contact)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setFullScreenIntent(pendingIntent, true)//设置全屏可弹出通知
                .build()
            notificationManager.notify(1, notification)
        }
    }

    //判断当前app是否在前台活跃
    private fun isForeground(): Boolean {
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (runningAppProcess in activityManager.runningAppProcesses) {
            if (runningAppProcess.processName == packageName) {
                //找到app进程
                //判断当前app运行的关键级,是否等于处于前台位置的关键级
                return runningAppProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
            }
        }
        return false
    }

    override fun onCreate() {
        super.onCreate()
        instance = this

        MultiDex.install(this)//接触65535方法数量限制
        //环信初始化
        EMClient.getInstance().init(applicationContext, EMOptions())
        //在做打包混淆时,关闭debug模式,避免消耗不必要的资源
        EMClient.getInstance().setDebugMode(BuildConfig.DEBUG)

        //Bmob初始化
        Bmob.initialize(applicationContext, "1110a460b142f192e04318d73d1c22a2")
        EMClient.getInstance().chatManager().addMessageListener(messageListener)

        soundPool.play(duan,1f,1f,0,0,1f)
        soundPool.play(yulu,1f,1f,0,0,1f)
    }
}